package com.blockmeta.bbs.businesslibrary.base.fragment;

import android.content.Context;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.interfaces.ITabAction;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

/**
 * Created by author on 2018/1/24.
 */

public abstract class BaseLazyListFragment extends BaseFragment implements ITabAction {

    /**
     * Fragment当前状态是否可见
     */
    protected boolean isVisible;
    public Context mContext;
    protected boolean isFirst = true;
    public View view;
    public SmartRefreshLayout list_swipe;
    public RecyclerView list_recy;

    protected boolean isCanLoad = false;
    protected boolean isLoad = false;

    @Override
    public void onAttach(Context context) {
        mContext = getActivity();
        super.onAttach(context);
    }

    //先于oncreatview执行的方法
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isCanLoad) {
            return;
        }

        if (getUserVisibleHint() && isFirst) {
            isFirst = false;
            initializationData();
            isLoad = true;
        } else {
            if (isLoad) {
                stopLoad();
            }
        }
    }

    protected void stopLoad() {

    }


    /**
     * 延迟加载
     */
    protected abstract void initializationData();

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_list_smart, null);
        list_swipe = (SmartRefreshLayout) view.findViewById(R.id.list_swipe);
        list_recy = (RecyclerView) view.findViewById(R.id.list_recy);
        list_swipe.setEnabled(false);//禁用下拉刷新
        list_swipe.setPrimaryColorsId(R.color.background_gray, R.color.text_black);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        list_recy.setLayoutManager(manager);
        isCanLoad = true;
        /**初始化的时候去加载数据**/
        isCanLoadData();
        return view;
    }

    @Override
    public void initView() {

    }

    @Override
    public void tabClickToMoveTop(){
        if(list_recy != null){
            list_recy.scrollToPosition(0);
        }
    }

    @Override
    public void tabClickToRefreshList(){
        tabClickToMoveTop();
        if(list_swipe != null){
            list_swipe.autoRefresh();
        }
    }
}
